package cn.easier.activity.console.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.easier.activity.console.entity.OptionParams;
import cn.easier.activity.console.entity.QuestionnaireParams;
import cn.easier.activity.console.service.ActivityConsoleService;
import cn.easier.activity.console.utils.ExcelUtil;
import cn.easier.activity.web.dto.QuestionnaireMessageDto;
import cn.easier.activity.web.entity.OptionMessage;
import cn.easier.activity.web.entity.QuestionnaireMessage;
import cn.easier.club.base.dto.ResultInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/activityMessage")
public class ActivityConsoleController {
    private static Logger logger = LoggerFactory.getLogger(ActivityConsoleController.class);

    private final ActivityConsoleService activityMessageService;

    public ActivityConsoleController(ActivityConsoleService activityMessageService) {
        this.activityMessageService = activityMessageService;
    }

    /**
     * 查看所有留言
     *
     * @return
     */
    @RequestMapping(value = "/getMessage", method = RequestMethod.GET)
    @ResponseBody
    public ResultInfo getMessage(@RequestParam(value = "activityId", required = false) Integer activityId,
                                 @RequestParam(value = "beginTime", required = false) String beginTime,
                                 @RequestParam(value = "endTime", required = false) String endTime,
                                 @RequestParam(value = "pageNum", required = true) int pageNum,
                                 @RequestParam(value = "pageSize", required = true) int pageSize) {
        List<Object> result = activityMessageService.getMessage(activityId, beginTime, endTime, pageNum, pageSize);
        Object o = result.get(result.size() - 1);
        result.remove(result.size() - 1);
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), String.valueOf(o), result);
    }

    /**
     * 查看活动选项留言
     *
     * @return
     */
    @RequestMapping(value = "/getInputMessage", method = RequestMethod.GET)
    @ResponseBody
    public ResultInfo getInputMessage(@RequestParam(value = "activityId", required = true) Integer activityId,
                                      @RequestParam(value = "pageNum", required = true) int pageNum,
                                      @RequestParam(value = "pageSize", required = true) int pageSize
    ) {
        return activityMessageService.getInputMessage(activityId, pageNum, pageSize);
    }

    /**
     * 所有活动名称
     *
     * @return
     */
    @RequestMapping(value = "/getActivityName", method = RequestMethod.GET)
    @ResponseBody
    public ResultInfo getActivityName() {
        return activityMessageService.getActivityName();
    }

    /**
     * 每日答题活动名称
     *
     * @return
     */
    @RequestMapping(value = "/getDailyActivityName", method = RequestMethod.GET)
    @ResponseBody
    public ResultInfo getDailyActivityName() {
        return activityMessageService.getDailyActivityName();
    }

    /**
     * 添加问卷相关信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addQuestionnaireMessage/{activityInfoId}", method = RequestMethod.POST)
    public ResultInfo addQuestionnaireMessage(@RequestBody @Valid List<QuestionnaireMessageDto> params, @PathVariable Integer activityInfoId) {
        return activityMessageService.questionnaireMessage(params, activityInfoId);
    }

    /**
     * 删除每日答题
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delMessage", method = RequestMethod.POST)
    public ResultInfo delMessage(@RequestParam(value = "type", required = false) String type, @RequestParam(value = "id", required = true) Long id) {
        return activityMessageService.delMessage(type, id);
    }

    /**
     * 获得问卷相关信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getQuestionnaireMessage", method = RequestMethod.GET)
    public ResultInfo getQuestionnaireMessage(@RequestParam(value = "activityId", required = false) String activityId) {
        return activityMessageService.getQuestionnaireMessage(activityId);
    }

    /**
     * 是否显示留言
     *
     * @return
     */
    @RequestMapping(value = "/showMessage", method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo showMessage(@RequestParam(value = "id", required = false) Long id, @RequestParam(value = "type", required = false) String type) {
        return activityMessageService.showMessage(id, type);
    }

    /**
     * 是否显示留言
     *
     * @return
     */
    @RequestMapping(value = "/getDailyMessage", method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo getDailyMessage(@RequestParam(value = "activityInfoId", required = false) Integer activityInfoId,
                                      @RequestParam(value = "pageNum", required = true) int pageNum,
                                      @RequestParam(value = "pageSize", required = true) int pageSize) {
        List<Object> result = activityMessageService.getDailyMessage(activityInfoId, pageNum, pageSize);
        Object o = result.get(result.size() - 1);
        result.remove(result.size() - 1);
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), String.valueOf(o), result);
    }

    @RequestMapping(value = "/importXls", method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo importXls(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "activityId", required = false) Integer activityId) throws IOException {
        if (file == null) {
            return new ResultInfo("ERROR", "请上传文件", null);
        }
        if (activityId == null || StringUtils.isBlank(activityId.toString())) {
            return new ResultInfo("ERROR", "无法获取到活动ID", null);
        }
        String type = file.getOriginalFilename();
        if (!type.endsWith(".xls") && !type.endsWith(".xlsx")) {
            return new ResultInfo("ERROR", "文件类型不正确", null);
        }
        Workbook Workbook = ExcelUtil.getWorkBook(file);
        if (Workbook == null) {
            return new ResultInfo("ERROR", "创建Excel工作簿为空！", null);
        }
        StringBuilder sb = new StringBuilder();
        try {
            List<Object> messageList = new ArrayList<>();
            List<Object> optionList = new ArrayList<>();
            ImportParams params = new ImportParams();
            for (int numSheet = 0; numSheet < Workbook.getNumberOfSheets(); numSheet++) {
                params.setTitleRows(0);
                params.setStartSheetIndex(numSheet);
                params.setNeedVerfiy(true);
                ExcelImportResult<Object> result = null;
                if (numSheet == 0) {
                    result = ExcelImportUtil.importExcelMore(file.getInputStream(),
                            QuestionnaireParams.class, params);
                    messageList = result.getList();
                } else if (numSheet == 1) {
                    result = ExcelImportUtil.importExcelMore(file.getInputStream(),
                            OptionParams.class, params);
                    optionList = result.getList();
                }
                List errorList = null;
                if (result.isVerfiyFail()) {
                    errorList = result.getFailList();
                    for (int i = 0; i < errorList.size(); i++) {
                        if (errorList.get(i) instanceof QuestionnaireMessage)
                            ExcelUtil.getWrongInfo(sb, errorList, i, errorList.get(i), "QuestionnaireParams", "QuestionnaireParams信息不符");
                        else if (errorList.get(i) instanceof OptionMessage)
                            ExcelUtil.getWrongInfo(sb, errorList, i, errorList.get(i), "OptionParams", "OptionParams信息不符");
                    }
                }
            }
            if (sb.length() != 0) {
                return new ResultInfo("ERROR", "导入信息有不符合规定的数据", sb);
            }
            ResultInfo message = activityMessageService.saveMessage(messageList, optionList, activityId);
            if (!message.getStatus().equals("SUCCESS")) {
                return new ResultInfo("ERROR", "保存失败！", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultInfo("ERROR", "导入失败!", null);
        }
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "导入成功!", null);
    }

    /**
     * 导出
     */
    @GetMapping("/export-excel")
    public void exportExcel(@RequestParam("activityId") String activityId, HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("调研问卷Excel");
        HSSFRow row0 = sheet.createRow(0);
        List<QuestionnaireMessage> questionnaire = activityMessageService.getQuestionnaire(activityId);
        List<String> titleList = new ArrayList<>();
        List<Long> idList = new ArrayList<>();
        titleList.add("序号");
        for (QuestionnaireMessage message : questionnaire) {
            titleList.add(message.getQuestionnaireName());
        }
        for (QuestionnaireMessage message : questionnaire) {
            idList.add(message.getId());
        }
        if (CollectionUtils.isEmpty(titleList)) {
            return;
        }
        titleList.add("提交时间");
        for (int j = 0; j < titleList.size(); j++) {
            HSSFCell cell = row0.createCell(j);
            cell.setCellValue(titleList.get(j));
        }
        HashMap<String, List<String>> returnMap = activityMessageService.getOption(questionnaire);
        for (int colIndex = 0; colIndex < questionnaire.size()+1; colIndex++) {
            String title;
            if (colIndex >= questionnaire.size()) {
                title = "提交时间";
            } else {
                title = questionnaire.get(colIndex).getQuestionnaireName();
            }
            List<String> list = returnMap.get(title);
            for (int rowIndex = 0; rowIndex < list.size(); rowIndex++) {
                HSSFRow row;
                if (colIndex == 0) {
                    row = sheet.createRow(rowIndex + 1);
                    HSSFCell cell = row.createCell(colIndex);
                    cell.setCellValue(rowIndex+1);
                } else {
                    row = sheet.getRow(rowIndex + 1);
                }
                HSSFCell cell = row.createCell(colIndex + 1);
                cell.setCellValue(list.get(rowIndex));
            }
        }
        sheet.autoSizeColumn((short) 0);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String("调研问卷".getBytes(), StandardCharsets.ISO_8859_1) + ".xls");
        workbook.write(response.getOutputStream());

    }
}


